import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//服务器端
public class UdpEchoServer {
    DatagramSocket datagramSocket = null;
    //构造方法
    public UdpEchoServer(int port) throws SocketException {
        datagramSocket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        //加while循环是为了可以多次接受返回信息
        while (true) {
            //1、读取请求并解析
            DatagramPacket requestpacket = new DatagramPacket(new byte[4090],4090);
            datagramSocket.receive(requestpacket);
                //为了方便在Java代码中处理 把他转化为String类型
            String request = new String(requestpacket.getData(),0,requestpacket.getLength());
            //2、根据请求计算响应
            String response = process(request);
            //3、把响应写回到客户端
            DatagramPacket responsepacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestpacket.getSocketAddress());
            datagramSocket.send(responsepacket);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
